<script lang="tsx" setup>
import AMapLoader from "@amap/amap-jsapi-loader";
import { ref, onMounted, onUnmounted, h } from "vue";
import { basePoints, specialPoints } from "@/mock/aMap/index";
import type { Point, PointGroup } from "@/typings/a-map";
import { useDesignStore } from "@/stores/module/design";
import { NButton } from "naive-ui";

const { VITE_APP_GD_KEY, VITE_APP_GD_SECRET, VITE_APP_GD_VERSION } = import.meta.env;

type WithNull<T> = T | null;

let map: any = null;
const aMapPoints = ref<AMap.LngLat[]>([]); //高德坐标系的点
let carMarker: WithNull<AMap.Marker> = null; //小车
let polyline: WithNull<AMap.Polyline> = null; //初始轨迹
let passedPolyline: WithNull<AMap.Polyline> = null; //走过的轨迹
let carInfoWindow: WithNull<AMap.InfoWindow> = null; //小车的carInfoWindow
let specialMarkers: AMap.Marker[] = [];
const speed = 100; //小车移动速度
const speedRate = 1;
const { getPrefixCls } = useDesignStore();
const prefixCls = getPrefixCls("aMap");

/** 初始化高德地图 */
const initMap = async () => {
  window._AMapSecurityConfig = {
    securityJsCode: VITE_APP_GD_SECRET,
  };
  try {
    const options = {
      key: VITE_APP_GD_KEY,
      version: VITE_APP_GD_VERSION,
      plugins: ["AMap.MoveAnimation"], // AMap.MoveAnimation 动画插件
    };
    //会自动在window上挂载AMap
    const AMap = await AMapLoader.load(options);
    map = new AMap.Map("mapContainer", {
      viewMode: "3D", // 是否为3D地图模式
      zoom: 17, // 初始化地图级别
      center: basePoints[0], // 初始化地图中心点位置
    });
  } catch (error: any) {
    window.$message.error(error);
  }
};

/** 转换高德坐标系 */
const convertLngLat = (lng: number, lat: number) => {
  return new AMap.LngLat(lng, lat);
};

/** 将所有点转换为高德坐标系的点 */
const getAMapPoints = (points: PointGroup) => {
  points.map((point) => {
    aMapPoints.value.push(convertLngLat(point[0], point[1]));
  });
};

/** 创建一个marker */
const createMarker = ({ map, position, icon, offset }: AMap.MarkerOptions) => {
  carMarker = new AMap.Marker({
    map,
    position,
    icon,
    offset,
  });
};

/** 小车信息窗体 */
const createCarInfoWindow = () => {
  carInfoWindow = new AMap.InfoWindow({
    offset: new AMap.Pixel(50, -20),
    autoMove: false, //是否自动调整窗体到视野内
    isCustom: true, //是否是自定义窗体
    content: "666",
  });
};

/** 添加特殊点 */
const createSpecialMarker = () => {
  specialMarkers = [];
  specialPoints.forEach((item, index) => {
    const specialMarker = new AMap.Marker({
      position: specialPoints[index],
      map: map,
      icon: new AMap.Icon({
        size: new AMap.Size(12, 12),
        image: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
        imageSize: new AMap.Size(12, 12),
      }),
      offset: new AMap.Pixel(-6, -6),
    });
    specialMarkers.push(specialMarker);
  });
};

/** 移除特殊点 */
const removeSpecialMarker = () => {
  map.remove(specialMarkers);
};

/** 绘制轨迹 */
const drawRoute = () => {
  //初始轨迹
  polyline = new AMap.Polyline({
    // @ts-ignore
    map: map,
    path: aMapPoints.value,
    strokeColor: "#333333",
    strokeOpacity: 1,
    strokeWeight: 4,
    lineJoin: "round",
  });
  // 走过的轨迹
  passedPolyline = new AMap.Polyline({
    // @ts-ignore
    map: map,
    strokeColor: "#1B6BFF",
    strokeOpacity: 1,
    strokeWeight: 4,
  });
};

/** 开始回放 */
const startMove = () => {
  carMarker?.moveAlong(aMapPoints.value, {
    autoRotation: true,
    speed,
  });
};

/** 暂停回放 */
const pauseMove = () => {
  carMarker?.pauseMove();
};

/** 继续播放 */
const resumeMove = () => {
  carMarker?.resumeMove();
};

/** 停止播放 */
const stopMove = () => {
  carMarker?.stopMove();
};

/** 监听小车运动 */
const subscribeMove = () => {
  //@ts-ignore
  carMarker?.on("moving", (e: any) => {
    passedPolyline?.setPath(e.passedPath);
  });
};

onMounted(async () => {
  await initMap();
  getAMapPoints(basePoints);
  drawRoute();
  createMarker({
    map: map,
    position: convertLngLat(basePoints[0][0], basePoints[0][1]),
    icon: "https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png",
    zIndex: 199,
    angle: 0, //marker的旋转角度
    offset: new AMap.Pixel(-13, -26),
  });
  subscribeMove();
});

onUnmounted(() => {
  map?.destroy();
});
</script>

<template>
  <div :class="prefixCls">
    <div class="control-panel">
      <NButton type="primary" @click="startMove">开始动画</NButton>
      <NButton type="primary" @click="pauseMove">暂停动画</NButton>
      <NButton type="primary" @click="resumeMove">继续动画</NButton>
      <NButton type="primary" @click="stopMove">停止动画</NButton>
      <NButton type="primary" @click="createSpecialMarker">添加点</NButton>
      <NButton type="primary" @click="removeSpecialMarker">移除点</NButton>
    </div>
    <div id="mapContainer"></div>
  </div>
</template>

<style lang="less" scoped>
@prefix-cls:~ "@{namespace}-aMap";
.@{prefix-cls} {
  position: relative;
  #mapContainer {
    width: 100%;
    height: 800px;
  }
  .control-panel {
    bottom: 0;
    right: 0;
    width: 200px;
    height: 150px;
    border: 1px solid black;
    position: absolute;
    z-index: 99;
    display: flex;
    align-items: center;
    justify-content: space-around;
    flex-wrap: wrap;
  }
  .car-info-window {
    width: 80px;
    height: 50px;
    background-color: #fff;
    opacity: 0.8;
  }
}
</style>
